package com.zdkj.subway.st.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.exceltools.IExcelExport;
import com.zdkj.common.core.util.R;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.dvo.SwPmTicketAreaDvo;
import com.zdkj.subway.st.dvo.SwPmTicketCardTypeDvo;
import com.zdkj.subway.st.dvo.SwPmTicketCardTypeParamDvo;
import com.zdkj.subway.st.entity.SwStStockDayCheckDetail;
import com.zdkj.subway.st.fegin.SubwaySupportService;
import com.zdkj.subway.st.service.SwStStockDayCheckDetailService;
import com.zdkj.subway.st.util.DateUtilsSt;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ProjectName: zdkj
 * @Package: com.zdkj.subway.st.controller
 * @ClassName: SwStStockDayCheckDetailController
 * @Description:
 * @Author: kangjian
 * @CreateDate: 2020/2/14 21:19
 * @Version: 1.0
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swStStockDayCheckDetail")
@Api(value = "swStStockDayCheckDetail", tags = "车票库存日盘点记录表")
public class SwStStockDayCheckDetailController {

    private static final Logger log = LoggerFactory.getLogger(SwStStockDayCheckDetailController.class);

    private final SwStStockDayCheckDetailService SwStStockDayCheckDetailService;
    @Autowired
    private SubwaySupportService subwaySupportService;

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(SwStStockDayCheckDetailService.getById(id));
    }

    @GetMapping("/page")
    public R<IPage> getDictPage(Page page, SwStStockDayCheckDetail swStStockDayCheckDetail) throws ParseException {
        LambdaQueryWrapper<SwStStockDayCheckDetail> lambdaQueryWrapper = Wrappers.query(swStStockDayCheckDetail).orderByDesc("ID").lambda();
        List<String> dateCondition = swStStockDayCheckDetail.getDates1();
        //结束日期+1 因为数据库时间存在小时分秒，所以结束日期+1
        if(dateCondition != null){
            String dateAddOne = DateUtilsSt.dateAddOne(dateCondition.get(1));
            if (ObjectUtil.isNotEmpty(dateCondition)) {
                lambdaQueryWrapper.and(wq -> wq.ge(SwStStockDayCheckDetail::getOutInGoingTime,dateCondition.get(0))
                        .lt(SwStStockDayCheckDetail::getOutInGoingTime,dateAddOne));
            }
        }
        return R.ok(SwStStockDayCheckDetailService.page(page, lambdaQueryWrapper));
    }

    @SysLog("日计划盘点表保存记录")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_stock_Day_detail_add')")
    public R save(@Valid @RequestBody SwStStockDayCheckDetail SwStStockDayCheckDetail) {
        PigxUser user = SecurityUtils.getUser();
        SwStStockDayCheckDetail.setCreatorId(user.getId());
        SwStStockDayCheckDetail.setCreatorName(user.getUsername());
        return R.ok(SwStStockDayCheckDetailService.save(SwStStockDayCheckDetail));
    }

    @SysLog("删除日计划盘点表记录")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_stock_Day_detail_delete')")
    public R removeById(@PathVariable String id) {
        return R.ok(SwStStockDayCheckDetailService.removeById(id));
    }

    @PutMapping
    @SysLog("修改日计划盘点表记录")
    @PreAuthorize("@pms.hasPermission('st_stock_Day_detail_update')")
    public R updateById(@Valid @RequestBody SwStStockDayCheckDetail SwStStockDayCheckDetail) {
        return R.ok(SwStStockDayCheckDetailService.updateById(SwStStockDayCheckDetail));
    }

    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('st_stock_Day_detail_export')")
    @SysLog("导出车票出入库与结存情况")
    public void exportExcel(SwStStockDayCheckDetail swStStockDayCheckDetail, HttpServletResponse response) {
        try {
            Map<Integer,SwPmTicketAreaDvo> swPmTicketAreaDvoMap = null;
            Map<String,SwPmTicketCardTypeParamDvo> swPmTicketCardTypeParamDvoMap = null;
            Map<String,SwPmTicketCardTypeDvo> swPmTicketCardTypeDvoMap = null;
            //查询票区名称字典 - 库区分区
            List<SwPmTicketAreaDvo> swPmTicketAreaDvo = (List<SwPmTicketAreaDvo>) subwaySupportService.getAreaDict().getData();
            if (CollectionUtil.isNotEmpty(swPmTicketAreaDvo)){
                swPmTicketAreaDvo = JSONObject.parseArray(JSONObject.toJSONString(swPmTicketAreaDvo),SwPmTicketAreaDvo.class);
                swPmTicketAreaDvoMap = swPmTicketAreaDvo.stream().collect(Collectors.toMap(SwPmTicketAreaDvo::getId, Function.identity(), (bean1, bean2) -> bean1));
            }
            //车票名称
            List<SwPmTicketCardTypeParamDvo> swPmTicketCardTypeParamDvos = (List<SwPmTicketCardTypeParamDvo>) subwaySupportService.getParamByMainAll().getData();
            if (CollectionUtil.isNotEmpty(swPmTicketCardTypeParamDvos)){
                swPmTicketCardTypeParamDvos = JSONObject.parseArray(JSONObject.toJSONString(swPmTicketCardTypeParamDvos),SwPmTicketCardTypeParamDvo.class);
                swPmTicketCardTypeParamDvoMap = swPmTicketCardTypeParamDvos.stream().collect(Collectors.toMap(SwPmTicketCardTypeParamDvo::getSubEnName, Function.identity(), (bean1, bean2) -> bean1));
            }
            //票种
            List<SwPmTicketCardTypeDvo> swPmTicketCardTypeDvos = (List<SwPmTicketCardTypeDvo>)subwaySupportService.getCardTypeDict().getData();
            if (CollectionUtil.isNotEmpty(swPmTicketCardTypeDvos)){
                swPmTicketCardTypeDvos = JSONObject.parseArray(JSONObject.toJSONString(swPmTicketCardTypeDvos),SwPmTicketCardTypeDvo.class);
                swPmTicketCardTypeDvoMap = swPmTicketCardTypeDvos.stream().collect(Collectors.toMap(SwPmTicketCardTypeDvo::getMainEnName, Function.identity(), (bean1, bean2) -> bean1));
            }
            LambdaQueryWrapper<SwStStockDayCheckDetail> lambdaQueryWrapper = Wrappers.query(swStStockDayCheckDetail).lambda();
            List<String> dateCondition = swStStockDayCheckDetail.getDates1();
            //结束日期+1 因为数据库时间存在小时分秒，所以结束日期+1
            if(dateCondition != null){
                String dateAddOne = DateUtilsSt.dateAddOne(dateCondition.get(1));
                if (ObjectUtil.isNotEmpty(dateCondition)) {
                    lambdaQueryWrapper.and(wq -> wq.ge(SwStStockDayCheckDetail::getOutInGoingTime,dateCondition.get(0))
                            .lt(SwStStockDayCheckDetail::getOutInGoingTime,dateAddOne));
                }
            }
            List<SwStStockDayCheckDetail> swStStockDayCheckDetaillist = SwStStockDayCheckDetailService.list(lambdaQueryWrapper);

            for (SwStStockDayCheckDetail stStockDayCheckDetail : swStStockDayCheckDetaillist) {
                if (CollectionUtil.isNotEmpty(swPmTicketAreaDvoMap) && StringUtils.isNotEmpty(stStockDayCheckDetail.getStockArea()) && swPmTicketAreaDvoMap.containsKey(Integer.valueOf(stStockDayCheckDetail.getStockArea()))){
                    stStockDayCheckDetail.setStockArea(swPmTicketAreaDvoMap.get(Integer.valueOf(stStockDayCheckDetail.getStockArea())).getTicketAreaName());
                }
                if (CollectionUtil.isNotEmpty(swPmTicketCardTypeParamDvoMap) && swPmTicketCardTypeParamDvoMap.containsKey(stStockDayCheckDetail.getTicketName())){
                    stStockDayCheckDetail.setTicketName(swPmTicketCardTypeParamDvoMap.get(stStockDayCheckDetail.getTicketName()).getSubName());
                }
                if (CollectionUtil.isNotEmpty(swPmTicketCardTypeDvoMap) && swPmTicketCardTypeDvoMap.containsKey(stStockDayCheckDetail.getTicketType())){
                    stStockDayCheckDetail.setTicketType(swPmTicketCardTypeDvoMap.get(stStockDayCheckDetail.getTicketType()).getMainName());
                }
            }
            IExcelExport excelExport = SpringContextHolder.getBean("commonExcelExport");//设置头信息
            Workbook workbook = excelExport.parse(swStStockDayCheckDetaillist);
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("", e);
        }
    }
}
